<template>
  <div class="order-export-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <i class="el-icon-download"></i>
        订单导出
      </h2>
      <p class="page-description">根据时间筛选导出订单数据，时间段最长为七天</p>
    </div>

    <!-- 导出设置 -->
    <div class="export-settings">
      <el-card>
        <div slot="header" class="card-header">
          <span>导出设置</span>
        </div>

        <el-form
          :model="exportForm"
          :rules="exportRules"
          ref="exportForm"
          label-width="120px">

          <!-- 横向排列的表单项 -->
          <el-row :gutter="20">
            <!-- 时间范围选择 -->
            <el-col :span="7">
              <el-form-item label="导出时间范围" prop="dateRange">
                <el-date-picker
                  v-model="exportForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  style="width: 100%">
                </el-date-picker>
                <div class="form-tip">
                  <i class="el-icon-info"></i>
                  时间段最长为七天
                </div>
              </el-form-item>
            </el-col>

            <!-- 订单状态筛选 -->
            <el-col :span="5">
              <el-form-item label="订单状态" prop="statue">
                <el-select v-model="exportForm.statue" placeholder="请选择订单状态" clearable style="width: 100%">
                  <el-option label="全部状态" :value="null"></el-option>
                  <el-option label="待支付" :value="0"></el-option>
                  <el-option label="已支付" :value="1"></el-option>
                  <el-option label="已取消" :value="-1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 商家筛选 -->
            <el-col :span="5">
              <el-form-item label="商家筛选" prop="merchantId">
                <el-input
                  v-model="exportForm.merchantId"
                  placeholder="请输入商家ID"
                  clearable
                  style="width: 100%">
                </el-input>
                <div class="form-tip">
                  <i class="el-icon-info"></i>
                  不填写则导出所有商家
                </div>
              </el-form-item>
            </el-col>
            <!-- 导出格式 -->
            <el-col :span="5">
              <el-form-item label="导出格式" prop="format">
                <el-radio-group v-model="exportForm.format">
                  <el-radio label="excel">Excel格式</el-radio>
                  <el-radio label="csv">CSV格式</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 操作按钮 - 单独一行靠右 -->
          <el-row>
            <el-col :span="24">
              <div class="button-container">
                <el-button
                  type="primary"
                  icon="el-icon-download"
                  :loading="exportLoading"
                  @click="handleExport">
                  开始导出
                </el-button>
                <el-button
                  icon="el-icon-refresh"
                  @click="handleReset">
                  重置
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>

    <!-- 导出历史 -->
    <div class="export-history">
      <el-card>
        <div slot="header" class="card-header">
          <span>导出历史</span>
          <el-button
            type="primary"
            icon="el-icon-refresh"
            size="small"
            @click="loadExportHistory">
            刷新
          </el-button>
        </div>

        <configurable-table
          :columns="historyColumns"
          :data="exportHistory"
          :loading="historyLoading"
          :show-pagination="true"
          :current-page.sync="historyPagination.current"
          :page-size.sync="historyPagination.size"
          :pagination-total="historyPagination.total"
          @page-change="loadExportHistory"
          stripe>
          <!-- 订单状态插槽 -->
          <template #statue="{ row }">
            <el-tag :type="getStatusType(row.statue)" size="small">
              {{ getStatusText(row.statue) }}
            </el-tag>
          </template>

          <!-- 导出格式插槽 -->
          <template #format="{ row }">
            <el-tag :type="row.format === 'excel' ? 'success' : 'info'" size="small">
              {{ row.format.toUpperCase() }}
            </el-tag>
          </template>

          <!-- 操作插槽 -->
          <template #actions="{ row }">
            <el-button
              type="text"
              size="small"
              @click="handleDownload(row)">
              下载
            </el-button>
          </template>
        </configurable-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import { exportOrderList, getExportLogList } from '@/api/admin/order-export'

export default {
  name: 'OrderExport',
  data() {
    return {
      exportLoading: false,
      historyLoading: false,

      // 导出表单
      exportForm: {
        dateRange: [],
        statue: null,
        merchantId: '',
        format: 'excel'
      },
      exportRules: {
        dateRange: [
          { required: true, message: '请选择导出时间范围', trigger: 'change' }
        ]
      },

      // 日期选择器配置
      pickerOptions: {
        disabledDate(time) {
          // 禁用未来日期
          return time.getTime() > Date.now()
        },
        onPick: ({ maxDate, minDate }) => {
          // 限制时间范围为7天
          if (minDate && maxDate) {
            const diffTime = Math.abs(maxDate - minDate)
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
            if (diffDays >= 7) {
              this.$message.warning('时间范围不能超过7天')
              this.exportForm.dateRange = []
            }
          }
        }
      },

      // 订单数据列配置（用于导出）
      orderColumns: [
        { prop: 'id', label: '订单ID', width: 160 },
        { prop: 'productId', label: '商品ID', width: 120 },
        { prop: 'productName', label: '商品名称', width: 200 },
        { prop: 'productPrice', label: '商品价格（元）', width: 120 },
        { prop: 'num', label: '商品数量', width: 96 },
        { prop: 'amount', label: '订单金额（元）', width: 120 },
        { prop: 'pointAmount', label: '积分金额（元）', width: 120 },
        { prop: 'payAmount', label: '支付金额（元）', width: 120 },
        { prop: 'statue', label: '订单状态', width: 96 },
        { prop: 'createTime', label: '下单时间', width: 160 },
        { prop: 'updateTime', label: '更新时间', width: 160 },
        { prop: 'attribute', label: '商品属性', width: 160 },
        { prop: 'cuserId', label: '用户ID', width: 120 }
      ],

      // 导出历史表格列配置
      historyColumns: [
        { prop: 'id', label: '导出ID', minWidth: 100 },
        {
          prop: 'startTime',
          label: '开始时间',
          minWidth: 120,
          formatter: (row, column, cellValue) => this.formatDate(cellValue)
        },
        {
          prop: 'endTime',
          label: '结束时间',
          minWidth: 120,
          formatter: (row, column, cellValue) => this.formatDate(cellValue)
        },
        { prop: 'statue', label: '订单状态', minWidth: 100, slot: 'statue' },
        { prop: 'merchantId', label: '商家ID', minWidth: 100 },
        { prop: 'recordCount', label: '导出记录数', minWidth: 120 },
        { prop: 'format', label: '导出格式', minWidth: 100, slot: 'format' },
        {
          prop: 'createTime',
          label: '导出时间',
          minWidth: 150,
          formatter: (row, column, cellValue) => this.formatDateTime(cellValue)
        },
        { prop: 'actions', label: '操作', minWidth: 120, slot: 'actions' }
      ],

      // 导出历史
      exportHistory: [],
      historyPagination: {
        current: 1,
        size: 10,
        total: 0
      }
    }
  },
  mounted() {
    this.loadExportHistory()
  },
  methods: {
    // 执行导出
    async handleExport() {
      try {
        await this.$refs.exportForm.validate()

        // 验证时间范围
        if (this.exportForm.dateRange && this.exportForm.dateRange.length === 2) {
          const startDate = new Date(this.exportForm.dateRange[0])
          const endDate = new Date(this.exportForm.dateRange[1])
          const diffTime = Math.abs(endDate - startDate)
          const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

          if (diffDays >= 7) {
            this.$message.error('时间范围不能超过7天')
            return
          }
        }

        this.exportLoading = true

        const params = {
          startTime: this.exportForm.dateRange[0] + ' 00:00:00',
          endTime: this.exportForm.dateRange[1] + ' 23:59:59'
        }

        // 添加状态筛选
        if (this.exportForm.statue !== null && this.exportForm.statue !== '') {
          params.statue = this.exportForm.statue
        }

        // 添加商家筛选
        if (this.exportForm.merchantId) {
          params.merchantId = parseInt(this.exportForm.merchantId)
        }

        Logger.log('=== 开始导出订单 ===')
        Logger.log('导出参数:', params)

        const response = await exportOrderList(params)
        Logger.log('导出响应:', response)

        if (response.code === 0 && response.data) {
          const orderData = response.data.list
          Logger.log('导出数据:', orderData)

          // 使用导出组件导出数据
          this.exportDataFile(orderData)

          this.$message.success(`导出成功，共导出 ${orderData.length} 条订单记录`)

          // 刷新导出历史
          this.loadExportHistory()
        } else {
          this.$message.error('导出失败：' + (response.msg || '未知错误'))
        }
      } catch (error) {
        Logger.error('导出订单失败:', error)
        this.$message.error('导出订单失败，请重试')
      } finally {
        this.exportLoading = false
      }
    },

    // 使用导出组件导出数据
    exportDataFile(orderData) {
      try {
        Logger.log('=== 准备导出数据 ===')

        // 使用 convertTableColumnsToExport 转换列配置
        const exportColumns = this.$convertTableColumnsToExport(
          this.orderColumns,
          {
            // 为需要格式化的列提供格式化函数
            productPrice: (value) => this.$formatAmount(value),
            amount: (value) => this.$formatAmount(value),
            pointAmount: (value) => this.$formatAmount(value),
            payAmount: (value) => this.$formatAmount(value),
            statue: (value) => this.getStatusText(value),
            createTime: (value) => this.$formatDateTime(value),
            updateTime: (value) => this.$formatDateTime(value)
          }
        )

        Logger.log('导出列配置:', exportColumns)

        // 生成文件名
        const startDate = this.exportForm.dateRange[0]
        const endDate = this.exportForm.dateRange[1]
        const fileName = `订单数据_${startDate}至${endDate}`

        Logger.log('文件名:', fileName)
        Logger.log('导出格式:', this.exportForm.format)
        Logger.log('数据条数:', orderData.length)

        // 使用导出工具导出
        this.$export(this.exportForm.format, orderData, exportColumns, fileName, {
          sheetName: '订单数据',
          textColumns: [0, 1, 12] // 订单ID、商品ID、用户ID设为文本格式，避免科学计数法
        })

        Logger.log('✅ 导出完成')
      } catch (error) {
        Logger.error('❌ 导出文件生成失败:', error)
        throw error
      }
    },

    // 加载导出历史
    async loadExportHistory() {
      this.historyLoading = true
      try {
        Logger.log('=== 加载导出历史 ===')

        const params = {
          pageIndex: this.historyPagination.current,
          pageSize: this.historyPagination.size
        }

        Logger.log('请求参数:', params)

        const response = await getExportLogList(params)

        Logger.log('导出历史响应:', response)

        if (response && response.code === 200) {
          const data = response.data || {}
          this.exportHistory = data.list || []
          this.historyPagination.total = data.total || 0

          Logger.log(`✅ 加载成功，共 ${this.exportHistory.length} 条记录，总计 ${this.historyPagination.total} 条`)
        } else {
          this.exportHistory = []
          this.historyPagination.total = 0
          Logger.warn('导出历史数据为空或格式异常')
        }
      } catch (error) {
        Logger.error('加载导出历史失败:', error)
        this.$message.error('加载导出历史失败：' + (error.message || '请重试'))
        this.exportHistory = []
        this.historyPagination.total = 0
      } finally {
        this.historyLoading = false
      }
    },

    // 下载文件
    handleDownload(row) {
      this.$message.info('下载功能需要后端提供文件下载接口')
    },

    // 重置表单
    handleReset() {
      this.exportForm = {
        dateRange: [],
        statue: null,
        merchantId: '',
        format: 'excel'
      }
      this.$refs.exportForm.clearValidate()
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: 'warning',  // 待支付
        1: 'success',  // 已支付
        '-1': 'info'   // 已取消
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        '-1': '已取消'
      }
      return statusMap[status] || '全部状态'
    },

    // 格式化日期（仅日期部分，用于历史记录表格）
    formatDate(date) {
      if (!date) return '-'
      if (typeof date === 'string' && date.includes('T')) {
        return date.split('T')[0]
      }
      return this.$formatDateTime(date).split(' ')[0]
    },

    // 格式化日期时间（用于历史记录表格）
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return this.$formatDateTime(dateTime)
    }
  }
}
</script>

<style scoped>
.order-export-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.export-settings {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-tip {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.form-tip i {
  margin-right: 4px;
}

.button-container {
  text-align: right;
  padding-top: 10px;
  border-top: 1px solid #e8e8e8;
  margin-top: 10px;
}

.export-history {
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .export-settings .el-form-item {
    margin-bottom: 16px;
  }

  .export-settings .el-date-picker {
    width: 100% !important;
  }

  .export-settings .el-select {
    width: 100% !important;
  }

  .export-settings .el-input {
    width: 100% !important;
  }
}
</style>
